package com.mxq.eclipse.mqtt.demo.subscribe;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 订阅回调类
 *
 * @author xiaoqiang
 * @date 2020-05-09 16:12
 */
@Slf4j
@Component
public class SubscribeCallback implements MqttCallback {

    private MqttSubscribeDto mqttSubscribeDto;

    @Autowired
    private SubscribeConnect subscribeConnect;

    public SubscribeCallback() {
    }

    public SubscribeCallback(MqttSubscribeDto mqttSubscribeDto) {
        this.mqttSubscribeDto = mqttSubscribeDto;
    }
    /**
     * 连接丢失
     * @param cause
     */
    @Override
    public void connectionLost(Throwable cause) {
        log.info("Subscribe connectLost");
        // 重连
        subscribeConnect.getConn(mqttSubscribeDto);
    }

    /**
     * 接收到主题消息
     * @param topic
     * @param message
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String content = new String(message.getPayload());
        log.info("接收消息主题:{},接收消息Qos:{},接收消息内容:{}",topic,message.getQos(),content);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

    }
}
